﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Tasks.Business;
using Tasks.Common;
using Tasks.Common.Entitys;
using System.Collections;
using Tasks.Core;
using Tasks.UI.Models.Home;
using Tasks.UI.Models.Article;
using Tasks.UI.Models;
using System.Resources;
using System.Xml.Serialization;
using MyLib.Util;
using Tasks.Common.Enum;


namespace Tasks.UI.Controllers
{

    [SysAuthorizeAttribute]
    public class HomeController : BaseController
    {

        /// <summary>
        /// 系统首页
        /// </summary>
        /// <returns></returns>
        public ActionResult Index(LoginModel model)
        {
            if (!Config.Installed)
                return RedirectToAction("index", "install");
            if (Config.SystemTheme == "default")
            {
                return View("~/Views/Home/Login.cshtml", model);
            }
            return View(model);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [ActionName("Index"), HttpPost]
        public ActionResult Login(LoginModel model)
        {
            ExecuteResult result = Config.Login(model.Account, model.Password);
            if (result.ResultNo == 1)
            {
                return RedirectToAction("Main");
            }
            else
            {
                model.Message = result.Message;
                return View(model);
            }
        }

        /// <summary>
        /// 退出登录
        /// </summary>
        /// <returns></returns>
        public ActionResult Logout()
        {
            Config.Logout();
            return RedirectToAction("Index");
        }



        /// <summary>
        /// 系统首页
        /// </summary>
        /// <returns></returns>
        [RequireLogin]
        public ActionResult Main2(MainModel model)
        {
            AccountBLL bll = BusinessFactory.Account;
            Account company = bll.GetAccount(Config.CurrentOperator.CompanyID);
            Account serviceCompany = bll.GetAccount(Config.CurrentOperator.ParentCompanyID);
            Account serviceUser = bll.GetAccount(company.CreateUserID);

            if (serviceCompany != null)
                model.ServiceCompany = serviceCompany.Name;
            if (serviceUser != null)
            {
                model.ServiceUser = serviceUser.Name;
                model.ServiceTel = serviceUser.MobileNo;
            }




            PowerBLL power = new PowerBLL(Config.CompanyID);
            if (Config.AdminID == Config.CurrentOperator.UserID)
            {
                model.MenuList = new BasedataBLL(0).GetAllMenus();
                model.Apps = power.GetAllApps();
                model.AppInfo = model.Apps.First();
            }
            else
            {
                model.Apps = power.GetAppsByUserID(Config.CurrentOperator.UserID);

                if (string.IsNullOrEmpty(model.App))
                {
                    model.App = model.Apps.Count > 0 ? model.Apps[0].AppID.ToString() : "0";
                }

                model.AppInfo = model.Apps.SingleOrDefault(t => t.AppID == int.Parse(model.App));
                model.MenuList = new BasedataBLL(0).GetUserMenus(Config.CurrentOperator.UserID, model.App);
            }

            if (model.Apps == null || model.Apps.Count == 0)
            {
                return Content("你没有访问权限，请找管理员给您分配系统权限");
            }

            //Account account = BusinessFactory.Account.GetAccount(Config.CurrentOperator.UserID);
            //if (account.UserType != (int)UserType.Employee)
            //{
            //    return Content("企业账号没有操作地接权限，请使用员工账号操作!");
            //}

            return View(model);
        }

        /// <summary>
        /// 系统首页
        /// </summary>
        /// <returns></returns>
        [RequireLogin]
        public ActionResult Main(MainModel model)
        {
            return View();
        }

        public ActionResult Welcome()
        {
            return View();
        }

        /// <summary>
        /// 系统登录后显示的第一个界面
        /// </summary>
        /// <returns></returns>
        public ActionResult First(FirstModel model)
        {
            ArticleBLL articleBLL = new ArticleBLL();
            Account account = BusinessFactory.Account.GetAccount(Config.CurrentOperator.UserID);
            model.ActionList = BusinessFactory.Power.GetActionsByUserID(Config.CurrentOperator.UserID);
            model.Module = BusinessFactory.Power.GetModuleByName("通知公告");
            model.LastLoginTime = account.LastLoginTime;
            model.AccountNo = account.AccountNo;
            model.PageIndex = model.PageIndex == 0 ? 1 : model.PageIndex;
            model.PageSize = 5;
            int rowsCount = 0;
            Hashtable condition2 = new Hashtable();
            condition2["OwnerID"] = Config.CompanyID;
            condition2["Type"] = (int)ArticleType.通知公告;
            model.NoticeList = articleBLL.Search(condition2, model.PageIndex, model.PageSize, out rowsCount);
            model.RowCount = rowsCount;
            if (model.NoticeList == null)
            {
                model.NoticeList = new List<Article>();
            }
            else
            {
                IList<PowerAction> actions = model.ActionList.Where(t => t.ModuleID == model.Module.ModuleID).ToList();
                Article art = new Article();
                foreach (Article arts in model.NoticeList.OrderBy(t => t.ActionID))
                {
                    foreach (PowerAction action in actions.OrderBy(t => t.ActionID))
                    {
                        if (action.ActionID == arts.ActionID)
                        {
                            art = articleBLL.GetArticleByLatestDate((int)ArticleType.通知公告, arts.ActionID, Config.CompanyID);
                        }
                    }
                }
                if (art.ActionID != 0)
                {
                    model.Title = art.Title;
                    model.Content = CommonUtil.NoHTML(art.Content).Trim();
                    model.CreateTime = art.CreateTime.ToShortDateString();
                    model.CreateUserName = art.CreateUserName;
                    model.ID = art.ID;
                }
            }

            #region 通知公告

            //ArticleBLL articleBLL = new ArticleBLL();
            //Hashtable condition2 = new Hashtable();
            //condition2["OwnerID"] = Config.CompanyID;
            //condition2["Type"] = (int)ArticleType.通知公告;
            //model.NoticeList = articleBLL.Search(condition2, model.PageIndex, model.PageSize, out rowsCount);
            //model.RowCount = rowsCount;
            //if (model.NoticeList == null)
            //{
            //    model.NoticeList = new List<Article>();
            //}
            //else
            //{
            //    Article art = articleBLL.GetArticleByLatestDate((int)ArticleType.通知公告);
            //    model.Title = art.Title;
            //    model.Content = CommonUtil.NoHTML(art.Content).Trim();
            //    model.CreateTime = art.CreateTime.ToShortDateString();
            //    model.CreateUserName = art.CreateUserName;
            //    model.ID = art.ID;
            //}

            #endregion

            return View(model);
        }


        /// <summary>
        /// 获取对象Json数据
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        public ActionResult GetFirstByJson(int ID)
        {
            ArticleBLL articleBLL = new ArticleBLL();
            Article Jsons = articleBLL.GetArticleByID(ID);
            string content = CommonUtil.NoHTML(Jsons.Content).Trim();
            Jsons.Content = content.Length > 155 ? content.Substring(0, 155) + "..." : content;

            Jsons.CreateDateStr = Jsons.CreateTime.ToShortDateString();
            if (Jsons == null)
                Jsons = new Article();
            return Json(Jsons);
        }


        /// <summary>
        /// 消息提醒页面
        /// </summary>
        /// <returns></returns>
        public ActionResult RemindList(NoticeReadStateModel model)
        {
            AccountBLL account = BusinessFactory.Account;
            if (model.NoticeIDValue != null)
            {
                //消息列表界面的全部设为已读按钮
                NoticeReadState notrederstate = new NoticeReadState();
                string NoticeIDValue = model.NoticeIDValue.TrimEnd(',');
                string[] NoticeIDCount = NoticeIDValue.ToString().Split(',');
                for (int i = 0; i < NoticeIDCount.Length; i++)
                {
                    notrederstate.NoticeID = Convert.ToInt32(NoticeIDCount[i]);
                    notrederstate.ReaderState = 1;
                    notrederstate.ReaderID = Config.CurrentOperator.UserID;
                    account.AddReaderState(notrederstate);
                    model.ReaderState = 2;
                }
            }
            model.PageSize = model.PageSize == 0 ? 20 : model.PageSize;
            int rowCount = 0;
            model.PageIndex = model.PageIndex == 0 ? 1 : model.PageIndex;
            Hashtable ht = new Hashtable();
            ht["ReaderID"] = Config.CurrentOperator.UserID;
            ht["ReaderState"] = model.ReaderState;
            model.NoticeList = account.NoticeList(ht, Config.CompanyID, model.PageSize, model.PageIndex, out rowCount);//消息列表
            model.RowCount = rowCount;
            if (model.NoticeList == null) model.NoticeList = new List<Notice>();

            return View(model);
        }

        public ActionResult AddNoticesReaderState(NoticeReadStateModel model)
        {
            //向阅读表添加阅读数据
            AccountBLL account = BusinessFactory.Account;
            Notice notice = new Notice();
            NoticeReadState notrederstate = new NoticeReadState();
            notrederstate.NoticeID = model.NoticeID;
            notrederstate.ReaderState = 1;
            notrederstate.ReaderID = Config.CurrentOperator.UserID;

            Hashtable ht = new Hashtable();
            ht["NoticeID"] = notrederstate.NoticeID;
            ht["ReaderID"] = notrederstate.ReaderID;
            int count = account.FindByReaderIDNoticeID(ht, Config.CompanyID);
            if (count == 0)//判断是否已经阅读
            {
                account.AddReaderState(notrederstate);
            }
            notice.NoticeUrl = account.GetNoticeByNoticeID(model.NoticeID).NoticeUrl;
            string[] NoticeUrl = notice.NoticeUrl.ToString().Split('/');
            return RedirectToAction(NoticeUrl[1], NoticeUrl[0]);
        }
        /// <summary>
        /// 获取未读消息数据
        /// </summary>
        /// <returns></returns>
        public ActionResult GetRemindCount(NoticeReadStateModel model)
        {
            AccountBLL accountbll = BusinessFactory.Account;
            int NoticeReadCount = accountbll.GetNoticeReadStateByReaderID(Config.CurrentOperator.UserID, Config.CompanyID);//获取已读消息条数
            int noticecount = accountbll.GetNoticeCount(Config.CompanyID);//获取消息总数
            if (NoticeReadCount < noticecount)
                return new ContentResult() { Content = "1" };
            else
                return new ContentResult() { Content = "0" };
        }
        /// <summary>
        /// 获取菜单数据
        /// </summary>
        /// <returns></returns>
        /// 
        [RequireLogin]
        public ActionResult GetMenuJsonData()
        {
            IList<Menu> menus = BusinessFactory.BasedataBLL.GetAllMenus();
            return Json(menus, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        ///  修改密码
        /// </summary>
        /// <returns></returns>
        /// 
        [HttpGet, RequireLogin]
        public ActionResult ChangePassword(LoginModel model)
        {
            return View(model);
        }

        [ActionName("ChangePassword"), HttpPost]
        public ActionResult doChangePassword(LoginModel model)
        {
            AccountBLL account = BusinessFactory.Account;
            Account accountmodel = new Account();
            model.UserID = Config.CurrentOperator.UserID;
            accountmodel = account.GetAccount(model.UserID);
            string oldPasswordTomd5 = SecurityUtil.EncryptToMD5(model.OldPassword);
            if (accountmodel.Password == oldPasswordTomd5)
            {
                if (model.NewPassword != "" && model.NewPassword != null)
                {
                    if (model.ConfirmPassword != "" && model.ConfirmPassword != null)
                    {
                        if (model.NewPassword == model.ConfirmPassword)
                        {
                            account.ModifyPassword(model.NewPassword, model.UserID);
                            model.Correct = "恭喜，您的密码已经成功修改";
                        }
                    }
                }
            }
            else
            {
                model.error = "×原密码不正确";
            }

            return View(model);
        }

        /// <summary>
        /// 错误提示页面
        /// </summary>
        /// <returns></returns>
        public ActionResult Error()
        {
            return View();
        }
    }
}
